package com.cloudfactory.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudfactory.po.ServiceCategory;
import com.cloudfactory.po.ServiceLabelRef;
import com.cloudfactory.vo.ServiceVo;

@Service
public class ServiceService {

	@Autowired
	private SqlSession sqlSession;

	public List<ServiceVo> selectAllServiceVo() {
		List<ServiceVo> result = new ArrayList<ServiceVo>();
		List<com.cloudfactory.po.Service> services = sqlSession
				.selectList("com.cloudfactory.service.selectAll");
		if (services != null) {
			for (com.cloudfactory.po.Service service : services) {
				result.add(getServiceVo(service));
			}
		}

		return result;
	}

	public ServiceVo selectServiceVoById(Long id) {
		return getServiceVo(sqlSession.selectOne("com.cloudfactory.service.selectById", id));
	}

	public List<ServiceCategory> selectAllCategory() {
		List<ServiceCategory> result = sqlSession.selectList("com.cloudfactory.service_category.selectAll");
		return result;
	}

	private ServiceVo getServiceVo(com.cloudfactory.po.Service service) {
		if (service == null) {
			return null;
		}
		ServiceVo serviceVo = new ServiceVo();
		serviceVo.setServiceId(service.getServiceId());
		serviceVo.setServiceName(service.getServiceName());
		serviceVo.setServiceIcon(service.getServiceIcon());
		serviceVo.setServiceDesc(service.getServiceDesc());
		List<ServiceLabelRef> serviceLabelRefs = sqlSession
				.selectList("com.cloudfactory.service_label_ref.selectByServiceId", service.getServiceId());
		if (serviceLabelRefs != null) {
			for (ServiceLabelRef serviceLabelRef : serviceLabelRefs) {
				serviceVo.addServiceLabel(sqlSession.selectOne("com.cloudfactory.service_label.selectNameById",
						serviceLabelRef.getLabelId()));
			}
		}
		return serviceVo;
	}

}
